package com.example.fangyimanagement;

import com.example.fangyimanagement.core.LoginUser;
import com.example.fangyimanagement.core.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/ymjzManage")
public class ymjzManageController {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 创建一个疫苗接种信息
     * @param param
     * @return
     */
    @RequestMapping("/addYmjz")
    public Result<Void> addYmjz(@RequestBody Map<String, String> param) {
        String name = param.get("name");
        String sfz = param.get("sfz");
        String districtCode = param.get("districtCode");
        String jzd = param.get("jzd");
        String ymFactory = param.get("ymFactory");
        String remark = param.get("remark");
        //        操作数据库
        String sql = "insert into ymjz_situation (name, sfz, district_code, jz_jzd, jz_time, ym_factory, remark) " +
                "values (?, ?, ?, ?, CURRENT_TIME, ?, ?)";
        int rows = this.jdbcTemplate.update(sql, name, sfz, districtCode, jzd, ymFactory, remark);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("添加失败");
        }
    }

    /**
     * 删除一个疫苗接种信息
     * @param param
     * @return
     */
    @RequestMapping("/deleteYmjz")
    public Result<Void> deleteYmjz(@RequestBody Map<String, String> param) {
        String id = param.get("id");
        //        操作数据库
        int rows = this.jdbcTemplate.update("delete from ymjz_situation where id =?", id);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("删除失败");
        }
    }

    /**
     * 修改疫苗接种的某一条信息
     * @param param
     * @return
     */
    @RequestMapping("/updateYmjz")
    public Result<Void> updateYmjz(@RequestBody Map<String, String> param) {
        String id = param.get("id");
        String name = param.get("name");
        String sfz = param.get("sfz");
        String districtCode = param.get("districtCode");
        String jzd = param.get("jzd");
        String ymFactory = param.get("ymFactory");
        String remark = param.get("remark");
        //        操作数据库
        String sql = "update ymjz_situation set name=?, sfz=?, district_code=?, jz_jzd=?, ym_factory=?, remark=? where id =?";
        int rows = this.jdbcTemplate.update(sql, name, sfz, districtCode, jzd, ymFactory,remark, id);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("编辑失败");
        }
    }

    /**
     * 疫苗接种信息列表查询
     * @param param
     * @param loginUser
     * @return
     */
    @RequestMapping("/ymjzList")
    public Result<List<Map<String, Object>>> ymjzList(@RequestBody Map<String, String> param, LoginUser loginUser) {
        String account = loginUser.getAccount();
        List<Map<String, Object>> accountRoleOrgList = this.jdbcTemplate.queryForList("SELECT name, role_code, org_code FROM glpt_user WHERE account=?", account);
        /**
         * 根据登录人账号找到了角色和组织编码，查数据时就要做权限控制
         */
        if (accountRoleOrgList.size() > 0) {
            String accountRole = (String) accountRoleOrgList.get(0).get("role_code");
            String accountOrg = (String) accountRoleOrgList.get(0).get("org_code");
            int page = Integer.parseInt(param.get("page"));
            int size = Integer.parseInt(param.get("size"));
            String name = param.get("name");
            String sfz = param.get("sfz");
            String districtCode = param.get("districtCode");
            String ymjzd = param.get("ymjzd");
            String ymFactory = param.get("ymFactory");
            String ymjzDateStart = param.get("ymjzDateStart");
            String ymjzDateEnd = param.get("ymjzDateEnd");
            String sql = "SELECT ymjz_situation.id, ymjz_situation.name, sfz, ymjz_situation.district_code AS districtCode, \n" +
                    "glpt_org.org_name AS districtName, " +
                    "jz_jzd AS jzd, ymjzd_data.name AS jzdName, \n" +
                    "       ymjz_situation.ym_factory AS ymFactoryCode, comm_dict.name AS ymFactoryName,\n" +
                    "       jz_time AS jzTime, ymjz_situation.remark" +
                    " FROM ymjz_situation\n" +
                    " JOIN glpt_org ON glpt_org.org_code = ymjz_situation.district_code\n" +
                    " JOIN comm_dict ON comm_dict.code = ymjz_situation.ym_factory\n" +
                    " JOIN ymjzd_data ON ymjzd_data.id = ymjz_situation.jz_jzd\n" +
                    "                                                \n" +
                    "                                                \n" +
                    "                                                \n" +
                    " WHERE 1=1 ";
            List<Object> paramList = new ArrayList<>();
            if (name != null && !name.isEmpty()) {
                sql = sql + " AND ymjz_situation.name like '%" + name + "%'";
            }
            if (sfz != null && !sfz.isEmpty()) {
                sql = sql + " AND sfz like '%" + sfz + "%'";
            }
            if (districtCode != null && !districtCode.isEmpty()) {
                sql = sql + " AND ymjz_situation.district_code = ?";
                paramList.add(districtCode);
            }
            if (ymjzd != null && !ymjzd.isEmpty()) {
                sql = sql + " AND jz_jzd = ?";
                paramList.add(ymjzd);
            }
            if (ymFactory != null && !ymFactory.isEmpty()) {
                sql = sql + " AND ym_factory = ?";
                paramList.add(ymFactory);
            }
            if (ymjzDateStart != null && !ymjzDateStart.isEmpty()) {
                sql = sql + " AND jz_time >= ?";
                paramList.add(ymjzDateStart);
            }
            if (ymjzDateEnd != null && !ymjzDateEnd.isEmpty()) {
                sql = sql + " AND jz_time <= ?";
                paramList.add(ymjzDateEnd);
            }
            /**
             * 如果是区级管理员，就要只查本区的范围
             * 如果是疫苗接种点管理员，只要查自己接种点的
             */
            if (accountRole.equals("district_manager") && accountOrg != null) {
                sql = sql + " AND ymjz_situation.district_code = ?";
                paramList.add(accountOrg);
            } else if (accountRole.equals("ymzsdManager")) {
                sql = sql + " AND ymjzd_data.manager_account = ?";
                paramList.add(account);
            }
            String countSql = "SELECT COUNT(1) FROM ("+ sql +") t";
            Integer count = this.jdbcTemplate.queryForObject(countSql, Integer.class, paramList.toArray());

            String querySql = sql + " ORDER BY id LIMIT ?, ?";
            paramList.add((page - 1) * size);
            paramList.add(size);
            List<Map<String, Object>> ymjzList = this.jdbcTemplate.queryForList(querySql, paramList.toArray());

            return Result.success(ymjzList).setTotal(count);
        } else {
            return Result.failed("查询失败，请稍后再试");
        }
    }

    /**
     * 移动端用户查询自己的疫苗接种记录
     * @param param
     * @return
     */
    @RequestMapping("/mobileUserYmjzList")
    public Result<List<Map<String, Object>>> mobileUserYmjzList(@RequestBody Map<String, String> param) {
            int page = Integer.parseInt(param.get("page"));
            int size = Integer.parseInt(param.get("size"));
            String name = param.get("name");
            String sfz = param.get("sfz");
            String districtCode = param.get("districtCode");
            String ymjzd = param.get("ymjzd");
            String ymFactory = param.get("ymFactory");
            String ymjzDateStart = param.get("ymjzDateStart");
            String ymjzDateEnd = param.get("ymjzDateEnd");
            String sql = "SELECT ymjz_situation.id, ymjz_situation.name, sfz, ymjz_situation.district_code AS districtCode, glpt_org.org_name AS districtName,\n" +
                    "       jz_jzd AS jzd, ymjzd_data.name AS jzdName, ymjz_situation.ym_factory AS ymFactoryCode, comm_dict.name AS ymFactoryName,\n" +
                    "       jz_time AS jzTime, ymjz_situation.remark" +
                    " FROM ymjz_situation\n" +
                    " JOIN glpt_org ON glpt_org.org_code = ymjz_situation.district_code\n" +
                    " JOIN comm_dict ON comm_dict.code = ymjz_situation.ym_factory\n" +
                    " JOIN ymjzd_data ON ymjzd_data.id = ymjz_situation.jz_jzd\n" +
                    " WHERE 1=1 ";
            List<Object> paramList = new ArrayList<>();
            if (name != null && !name.isEmpty()) {
                sql = sql + " AND ymjz_situation.name like '%" + name + "%'";
            }
            if (sfz != null && !sfz.isEmpty()) {
                sql = sql + " AND sfz like '%" + sfz + "%'";
            }
            if (districtCode != null && !districtCode.isEmpty()) {
                sql = sql + " AND ymjz_situation.district_code = ?";
                paramList.add(districtCode);
            }
            if (ymjzd != null && !ymjzd.isEmpty()) {
                sql = sql + " AND jz_jzd = ?";
                paramList.add(ymjzd);
            }
            if (ymFactory != null && !ymFactory.isEmpty()) {
                sql = sql + " AND ym_factory = ?";
                paramList.add(ymFactory);
            }
            if (ymjzDateStart != null && !ymjzDateStart.isEmpty()) {
                sql = sql + " AND jz_time >= ?";
                paramList.add(ymjzDateStart);
            }
            if (ymjzDateEnd != null && !ymjzDateEnd.isEmpty()) {
                sql = sql + " AND jz_time <= ?";
                paramList.add(ymjzDateEnd);
            }
            String countSql = "SELECT COUNT(1) FROM ("+ sql +") t";
            Integer count = this.jdbcTemplate.queryForObject(countSql, Integer.class, paramList.toArray());

            String querySql = sql + " ORDER BY id DESC LIMIT ?, ?";
            paramList.add((page - 1) * size);
            paramList.add(size);
            List<Map<String, Object>> ymjzList = this.jdbcTemplate.queryForList(querySql, paramList.toArray());

            return Result.success(ymjzList).setTotal(count);
    }

    /**
     * 根据组织编码查询该组织下有哪些疫苗接种点
     * @param param
     * @return
     */
    @RequestMapping("/getYmjzdDicts")
    public Result<List<Map<String, Object>>> getYmjzdDicts(@RequestBody Map<String, String> param) {
        String orgCode = param.get("orgCode");
        List<Object> paramList = new ArrayList<>();
        String sql = "SELECT id AS code, name FROM ymjzd_data";
        if (orgCode != null && !orgCode.isEmpty()) {
            sql = sql + " WHERE district_code = ?";
            paramList.add(orgCode);
        }
        List<Map<String, Object>> ymjzdList = this.jdbcTemplate.queryForList(sql, paramList.toArray());
        return Result.success(ymjzdList);
    }
    /**
     * 我管理的疫苗接种点
     * @param param
     * @param loginUser
     * @return
     */
    @RequestMapping("/myYmjzdList")
    public Result<List<Map<String, Object>>> myYmjzdList(@RequestBody Map<String, String> param, LoginUser loginUser) {
        String manager = loginUser.getAccount();
        String sql = "SELECT ymjzd_data.id AS id, ymjzd_data.name, " +
                "ymjzd_data.district_code AS districtCode, glpt_org.org_name AS districtName, " +
                "ymjzd_data.manager_account, glpt_user.name AS managerName, " +
                "address_detail AS addressDetail, " +
                "morning_open_time AS openTime, evening_close_time AS closeTime, window_num AS windowNum, status FROM ymjzd_data " +
                "JOIN glpt_user ON ymjzd_data.manager_account = glpt_user.account " +
                "JOIN glpt_org ON ymjzd_data.district_code = glpt_org.org_code WHERE 1=1 ";
        List<Object> paramList = new ArrayList<>();
        if (manager != null && !manager.isEmpty()) {
            sql = sql + " AND ymjzd_data.manager_account = ?";
            paramList.add(manager);
        }
        sql = sql + " ORDER BY ymjzd_data.id";
        List<Map<String, Object>> ymjzdList = this.jdbcTemplate.queryForList(sql, paramList.toArray());
        return Result.success(ymjzdList);
    }

    /**
     * 所有疫苗接种点的负责人列表
     * @param param
     * @return
     */
    @RequestMapping("/getManagerList")
    public Result<List<Map<String, Object>>> getManagerList(@RequestBody Map<String, String> param) {
        String sql = "SELECT name, account AS code FROM glpt_user WHERE role_code = 'ymzsdManager'";
        List<Map<String, Object>> managerList = this.jdbcTemplate.queryForList(sql);
        return Result.success(managerList);
    }
}
